import axios from "axios";
// import qs from 'qs'
import { getToken } from "./store";
import { message } from "ant-design-vue";

axios.defaults.baseURL = "http://106.14.139.101:8080";
// axios.defaults.baseURL = "http://81.69.185.190:8082/pro_api";
// axios.defaults.baseURL = "http://81.69.185.190:8082";

// axios.defaults.timeout = 30000

axios.defaults.headers.post["Content-Type"] = "application/json";

axios.interceptors.request.use(
  (config) => {
    if (config.method.toLocaleUpperCase() === "POST") {
      // config.data = qs.stringify(config.data)
    }
    // config.headers["Content-type"] = "application/json;charset=UTF-8"
    const token = getToken();
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error && error.response) {
      message.error(error.response.data.message);
    }
  }
);

function post(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function downLoadFile(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params, responseType: "arraybuffer" }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function uploadFile(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function deletefn(url, params) {
  return new Promise((resolve, reject) => {
    axios({
      method: "delete",
      url: url,
      params: params,
      data: params,
    }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

export { get, post, downLoadFile, deletefn, uploadFile };
